//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.yonyou.ucf.mdd.ext.login.util;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.bip.user.service.IGlobalizationPreferenceService;
import com.yonyou.diwork.service.session.extend.vo.UserIdentityVO;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.ml.vo.LanguageVO;
import com.yonyou.ucf.mdd.common.exceptions.message.MddLoginMsgException;
import com.yonyou.ucf.mdd.common.exceptions.message.MsgExceptionCode;
import com.yonyou.ucf.mdd.common.utils.json.GsonHelper;
import com.yonyou.ucf.mdd.core.developer.tool.Tracker;
import com.yonyou.ucf.mdd.ext.base.tenant.Tenant;
import com.yonyou.ucf.mdd.ext.base.user.User;
import com.yonyou.ucf.mdd.ext.base.user.UserType;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dubbo.DubboReferenceUtils;
import com.yonyou.ucf.mdd.ext.exceptions.BusinessException;
import com.yonyou.ucf.mdd.ext.login.user.LoginUserService;
import com.yonyou.ucf.mdd.ext.model.LoginUser;
import com.yonyou.ucf.mdd.ext.util.TenantUtils;
import com.yonyou.ucf.mdd.ext.util.login.BaseYhtUserUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.imeta.biz.base.Objectlizer;
import org.imeta.core.lang.BooleanUtils;
import org.imeta.orm.base.BizObject;
import org.imeta.orm.base.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class YhtUserUtil extends BaseYhtUserUtil {
    private static final Logger logger = LoggerFactory.getLogger(YhtUserUtil.class);
    private static String[] sensitiveDataArray = new String[]{"salt", "password", "defaultorg", "defaultstore"};
    private static final String USER_ENTITY = "base.user.User";

    public YhtUserUtil() {
    }

    public static User getUserByNewYhtAccessToken(String accessToken) throws Exception {
        logger.error("com.yonyou.ucf.mdd.ext.login.util.YhtUserUtil.getUserByNewYhtAccessToken 该接口已废弃，不需要在用token获取用户信息，请检查业务");
        throw new BusinessException("com.yonyou.ucf.mdd.ext.login.util.YhtUserUtil.getUserByNewYhtAccessToken 该接口已废弃，不需要在用token获取用户信息，请检查业务");
    }

    private static void removeSensitiveDate(User user) {
        if (null != user) {
            String[] var1 = sensitiveDataArray;
            int var2 = var1.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                String sensitiveDataKey = var1[var3];
                user.remove(sensitiveDataKey);
            }

            if (user.getUserType() != null && (user.getUserType().getValue() == UserType.TenantShopuser.getValue() || user.getUserType().getValue() == UserType.JoinUser.getValue())) {
                user.remove("shop");
            }

        }
    }

    public static Tenant getTenant(User user, String yhtTenantId) throws Exception {
        Tenant tenant;
        try {
            if (!AppContext.confOnlyYht()) {
                tenant = TenantUtils.getSubTenant(user.getTenant());
                Tracker.recordLogClues("com.yonyou.ucf.mdd.ext.login.util.YhtUserUtil", "getTenant", user.getTenant(), tenant, " 租户都从本域查结果");
                if (null != tenant) {
                    return tenant;
                }
            }
        } catch (Exception var3) {
            logger.error("getSubTenant", var3);
        }

        tenant = new Tenant();
        tenant.setYxyTenantId(yhtTenantId);
        tenant.setId(user.getTenant());
        tenant.setTenantCenter(yhtTenantId);
        tenant.setId(yhtTenantId);
        tenant.setIsOpen(true);
        return tenant;
    }

    public static boolean isOpenTenant(User user) {
        try {
            if (!AppContext.confOnlyYht()) {
                Tenant tenant = TenantUtils.getSubTenant(user.getTenant());
                Tracker.recordLogClues("com.yonyou.ucf.mdd.ext.login.util.YhtUserUtil", "getTenant", user.getTenant(), tenant, " 租户都从本域查结果");
                if (null != tenant) {
                    return tenant.getOpen();
                }
            }

            return true;
        } catch (Exception var2) {
            logger.error("getSubTenant", var2);
            return false;
        }
    }

    public static boolean isAdmin(LoginUser user) {
        return user.getUserType() == UserType.TenantAdmin || user.getUserType() == UserType.PlatForm;
    }

    public static boolean isAdmin() {
        UserType userType = getUserType();
        return userType == UserType.TenantAdmin || userType == UserType.PlatForm;
    }

    private static UserType getUserType() {
        String userType = InvocationInfoProxy.getUserType();
        if (StringUtils.isBlank(userType)) {
            return UserType.TenantEmployee;
        } else {
            Number v = Integer.parseInt(userType);
            return UserType.find(v);
        }
    }

    public static String getSingleOrg(LoginUser user) {
        if (AppContext.isShopUser(user)) {
            return user.getDocId();
        } else {
            boolean isSingleOrg = BooleanUtils.b(user.getIsSingleOrg());
            String orgId = null;
            if (isSingleOrg) {
                orgId = user.getOrgId();
            }

            return orgId;
        }
    }

    /**
     * 从工作台获取dataformat
     * @return
     */
    public static String getDataFormatFromGZT(){
//        IGlobalizationPreferenceService globalizationPreferenceService = AppContext.getBean(IGlobalizationPreferenceService.class);
        IGlobalizationPreferenceService globalizationPreferenceService = DubboReferenceUtils.getDubboService(IGlobalizationPreferenceService.class,"bip-user", null);

        if (null != globalizationPreferenceService){
            return globalizationPreferenceService.getDataformat(InvocationInfoProxy.getTenantid(), InvocationInfoProxy.getUserid());
        }
        return null;
    }

    public static Map geYhtUserMap(Map<String, Object> yhtUserMap) {
        Object yhtUserObj = yhtUserMap.get("user");
        return null != yhtUserObj && yhtUserMap instanceof Map ? (Map)yhtUserObj : null;
    }

    public static User queryUserObject(Object yhtUserId, Object yhtTenantId, Object docId, Object userType) {
        long startTime = System.currentTimeMillis();

        User var8;
        try {
            LoginUserService loginUserService = getLoginUserService(YhtUserUtil.LoginUserEnum.BASE_DOMAIN);
            if (null == loginUserService) {
                throw new MddLoginMsgException(MsgExceptionCode.NO_BEAN_FOUND, new String[]{"loginUserService"});
            }

            Map params = new HashMap();
            params.put("yhtUserId", yhtUserId);
            params.put("yhtTenantId", yhtTenantId);
            params.put("docId", docId);
            params.put("userType", userType);
            var8 = loginUserService.getLoginUser(params);
        } finally {
            logger.info("queryUserObject耗时：", startTime);
        }

        return var8;
    }

    public static User getBizObjectByUserMap(Map<String, Object> yhtUserMap) {
        User bizUserObject = new User();
        if (null == yhtUserMap) {
            return bizUserObject;
        } else {
            bizUserObject.put("lang", yhtUserMap.get("lang"));
            bizUserObject.setYhtUserId((String)yhtUserMap.get("userId"));
            bizUserObject.setName((String)yhtUserMap.get("userName"));
            bizUserObject.setCode((String)yhtUserMap.get("userCode"));
            bizUserObject.setMobile((String)yhtUserMap.get("userMobile"));
            bizUserObject.setEmail((String)yhtUserMap.get("userEmail"));
            return bizUserObject;
        }
    }

    public static User getBizObjectByTenantMap(Map<String, Object> tenantMap) {
        User bizObject = new User();
        bizObject.set("yhtTenantId", tenantMap.get("tenantId"));
        bizObject.set("yTenantId", tenantMap.get("tenantId"));
        bizObject.set("locale", tenantMap.get("locale"));
        setStringIntoBizObject(bizObject, "orgId", tenantMap.get("orgId"));
        setStringIntoBizObject(bizObject, "singleOrgId", tenantMap.get("orgId"));
        setStringIntoBizObject(bizObject, "syscode", tenantMap.get("syscode"));
        setStringIntoBizObject(bizObject, "docId", tenantMap.get("docId"));
        bizObject.set("identities", tenantMap.get("identities"));
        bizObject.set("defaultOrg", tenantMap.get("defaultOrg"));
        if (null != tenantMap.get("userType")) {
            bizObject.put("userType", Short.valueOf(tenantMap.get("userType").toString()));
        }

        setDateIntoBizObject(bizObject, "businessDate", tenantMap.get("businessDate"));
        if (null == bizObject.get("userType")) {
            Object userType = tenantMap.get("isAdmin");
            if (null != userType && "1".equals(userType.toString())) {
                bizObject.put("userType", UserType.TenantAdmin.getValue());
            } else {
                bizObject.put("userType", UserType.TenantEmployee.getValue());
            }
        }

        if (tenantMap.get("dimension") != null && tenantMap.get("dimension") instanceof JSONObject) {
            JSONObject dimension = (JSONObject)tenantMap.get("dimension");
            bizObject.set("docType", dimension.get("docType"));
        }

        if (tenantMap.get("dataformat") != null) {
            try {
                bizObject.put("dataformat", JSONObject.parseObject((String)tenantMap.get("dataformat")));
            } catch (Exception var7) {
                logger.error("dataformat ={}", tenantMap.get("dataformat"), var7);
            }
        }

        if (AppContext.isShopUser(bizObject)) {
            bizObject.set("isSingleOrg", true);
        } else {
            bizObject.set("isSingleOrg", tenantMap.get("isSingleOrg"));
        }

        String multiListStr = (String)tenantMap.get("multilist");
        if (multiListStr != null && GsonHelper.isGoodJson(multiListStr)) {
            List<LanguageVO> list = JSONObject.parseArray(multiListStr, LanguageVO.class);
            LinkedList<LanguageVO> linkedList = new LinkedList();
            linkedList.addAll(list);
            bizObject.set("LANGVO_LIST", linkedList);
            if (CollectionUtils.isEmpty(list)) {
                logger.error("YhtUserUtil.getBizObjectByTenantMap 解析语种信息为空: " + multiListStr);
                throw new MddLoginMsgException(MsgExceptionCode.MULTILANG_LANGVO_EMPTY);
            }

            Iterator var5 = list.iterator();

            while(var5.hasNext()) {
                LanguageVO LanguageVO = (LanguageVO)var5.next();
                if (LanguageVO.isDefault()) {
                    bizObject.set("DEFAULT_LANGVO", LanguageVO);
                    break;
                }
            }
        }

        bizObject.set("timezone", tenantMap.get("timezone"));
        bizObject.set("multilingualFlag", BooleanUtils.b(tenantMap.get("multilingualFlag"), true));
        bizObject.set("yht_isAdmin", tenantMap.get("yht_isAdmin"));
        bizObject.set("newArch", tenantMap.get("newArch"));
        return bizObject;
    }

    private static void setStringIntoBizObject(BizObject bizObject, String key, Object value) {
        if (null != value) {
            bizObject.put(key, value.toString());
        }
    }

    private static void setDateIntoBizObject(BizObject bizObject, String key, Object value) {
        if (null != value) {
            Date date = new Date((String)value);
            bizObject.put(key, date);
        }
    }

    public static Map getYhtTenantMap(Map<String, Object> yhtUserMap) {
        Object yhtTenantObj = yhtUserMap.get("tenant");
        if (yhtTenantObj == null) {
            return null;
        } else if (yhtTenantObj instanceof Map) {
            Map yhtTenantMap = (Map)yhtTenantObj;
            if (null == yhtTenantMap.get("tenantId")) {
                throw new MddLoginMsgException(MsgExceptionCode.YHT_SDK_NO_TENANTID);
            } else {
                return yhtTenantMap;
            }
        } else {
            return null;
        }
    }

    private static User getUserIdentity(List<UserIdentityVO> userIdentityVOS) {
        if (CollectionUtils.isEmpty(userIdentityVOS)) {
            throw new MddLoginMsgException(MsgExceptionCode.LOGIN_USER_IDENTITY_ISEMPTY);
        } else {
            UserIdentityVO userIdentity = (UserIdentityVO)userIdentityVOS.get(0);
            User user = (User)Objectlizer.decodeObj(new Json(GsonHelper.ToJSon(userIdentity)), "base.user.User");
            return user;
        }
    }

    private static LoginUserService getLoginUserService(YhtUserUtil.LoginUserEnum loginUserEnum) {
        switch(loginUserEnum) {
            case YHT:
            case LOCAL:
            case BASE_DOMAIN:
                return (LoginUserService)AppContext.getBean("defaultLoginUserService");
            default:
                return (LoginUserService)AppContext.getBean("defaultLoginUserService");
        }
    }

    private static enum LoginUserEnum {
        BASE_DOMAIN,
        YHT,
        LOCAL;

        private LoginUserEnum() {
        }
    }
}
